package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.Type;
import com.example.service.TypeService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("types")
public class TypeController {

    @Autowired
    private TypeService typeService;


    /**
     * 泳池类型分页查询
     * @return
     */
    @GetMapping("/getPageType/{current}/{size}")
    public R getPageType(@PathVariable int current,@PathVariable int size,Type type){


        IPage page =new Page(current,size);
        LambdaQueryWrapper<Type> lqw =new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(type.getTypeName()),Type::getTypeName,type.getTypeName());

        IPage page1 = typeService.page(page,lqw);

        return R.success("泳池类型分页查询!！",page1);
    }

    /**
     * 查询所有泳池类型
     * @return
     */
    @GetMapping("/getAllType")
    public R getAllType(){

        List<Type> list = typeService.list();
        return R.success("查询所有泳池类型！",list);
    }

    /**
     * 添加泳池类型
     * @return
     */
    @PostMapping("/addType")
    public R addType(@RequestBody Type type){

        LambdaQueryWrapper<Type> lqw =new LambdaQueryWrapper<>();
        lqw.eq(Strings.isNotEmpty(type.getTypeName()),Type::getTypeName,type.getTypeName());
        //1.查询数据库此泳池类型是否存在
        Type one = typeService.getOne(lqw);

        //2.不存在在添加
        if (one==null){
            boolean save = typeService.save(type);
            if (save){
                return R.success("添加泳池类型成功！",null);
            }else {
                return R.error("添加泳池类型失败！");
            }
        }else {
            //3.存在
            return R.error("泳池类型存在！添加失败！");
        }
    }

    /**
     * 通过id修改泳池类型
     * @return
     */
    @PutMapping("/updateType")
    public R updateType(@RequestBody Type type){
        boolean b = typeService.updateById(type);
        if (b){
           return R.success("通过id修改泳池类型成功",type);
        }else {
           return R.error("通过id修改泳池类型失败！");
        }
    }

    /**
     * 通过id删除泳池类型
     * @return
     */
    @DeleteMapping("/deleteType/{id}")
    public R deleteType(@PathVariable int id){

        boolean b = typeService.removeById(id);
        if (b){
           return R.success("通过id删除泳池类型成功",id);
        }else {
           return R.error("通过id删除泳池类型失败！");
        }
    }

}

